package com.example.book_subscribe.common.controlle;

import com.example.book_subscribe.common.utils.AliOssUtil;
import com.example.book_subscribe.common.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileUploadControll {
        @Autowired
        private AliOssUtil aliOssUtil;
        @PostMapping("/upload")
        public ResponseResult<?> uploadFile(@RequestParam("file") MultipartFile file) {
            try {
                // 获取原始文件名并处理特殊字符
                String originalFilename = file.getOriginalFilename();
                String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
                // 上传到OSS
                String url = aliOssUtil.upload(file.getBytes(), "bookFile/" + fileName);
                return ResponseResult.okResult(url);
            } catch (IOException e) {
                throw new RuntimeException("文件读取失败");
            }
        }
}